package org.msss.sprites;

/*
 * This is probably one of the most important classes, so it could use a lot of fixing
 * and making the code cleaner.
 */

import org.msss.gamebasic.*;
import static org.msss.gamebasic.Game.*;

/**
 * The player...
 * 
 * @author alanxoc3
 * 
 */
public class Player extends Sprite {

	private final int acceleration = 3;
	private final double friction = .25;
	private double xSpeed, ySpeed;
	
	private Direction director;
	private Moving mover;
	private MouseGrid grid;
	private RightHand hand1;
	private LeftHand hand2;
	private Feet feet;
	private Head head;

	@Override
	public void create() {
		
		director = new Direction();
		mover = new Moving();
		grid = new MouseGrid();
		
		hand1 = new RightHand();
		hand2 = new LeftHand();
		feet = new Feet();
		head = new Head();

		Game.room.addSprite(director);
		Game.room.addSprite(mover);
		Game.room.addSprite(grid);
		
		Game.room.addSprite(hand1);
		Game.room.addSprite(hand2);
		Game.room.addSprite(feet);
		Game.room.addSprite(head);

		this.setAnimationOn(true);

		setZ(0);
		setVisible(false);

		xSpeed = 0;
		ySpeed = 0;
	}

	@Override
	public void move() {
		addSpeed();
		addFriction();
		
		grid.setDirection(director.getDirection());
		head.setDirection(director.getDirection());
		feet.setDirection(director.getDirection());
		hand1.setDirection(director.getDirection());
		hand2.setDirection(director.getDirection());
		
		hand1.gridDirection(grid.getMGX(), grid.getMGY());
		hand2.gridDirection(grid.getMGX(), grid.getMGY());

		//Set the player's coordinates.
		setX(getX() + (int) xSpeed);
		setY(getY() + (int) ySpeed);

		//Set the coordinates of the body parts.
		head.setX(getX());
		head.setY(getY());
		
		feet.setX(getX());
		feet.setY(getY());
		
		hand1.setX(getX());
		hand1.setY(getY());
		
		hand2.setX(getX());
		hand2.setY(getY());
		
		view.setX(getX() - view.getW()/2 + 20);
		view.setY(getY() - view.getH()/2  + 20);
	}

	public void addSpeed() {
		int xMove = mover.getRightRun()*acceleration - mover.getLeftRun()*acceleration;
		int yMove = mover.getDownRun()*acceleration - mover.getUpRun()*acceleration;
		xSpeed += xMove;
		ySpeed += yMove;
		
		if (xMove !=0 || yMove != 0) {
			feet.setAnimationOn(true);
		} else {
			feet.setAnimationOn(false);
		}
	}
	
	/**
	 * Adds friction to the player.
	 */
	public void addFriction() {
		xSpeed = xSpeed - xSpeed * friction;
		ySpeed = ySpeed - ySpeed * friction;
	}
}
